﻿using RpcClient;
using RpcHelper;
using RpcModel;
using RpcModularModel.IpBlack;
using Wedonek.RpcStore.Service.DAL;
using Wedonek.RpcStore.Service.Interface;
using Wedonek.RpcStore.Service.Model;

namespace Wedonek.RpcStore.Service.Collect
{
    internal class IpBlackCollect : BasicCollect<IpBlackListDAL>, IIpBlackCollect
    {
        public IpBlackDatum[] Query(IpBlackQuery query, IBasicPage paging, out long count)
        {
            return base.BasicDAL.Query(query, paging, out count);
        }
        public IpBlackDatum Get(int id)
        {
            IpBlackDatum black = base.BasicDAL.Get(id);
            if (black == null)
            {
                throw new ErrorException("rpc.store.ipBlack.not.find");
            }
            return black;
        }
        public void SetRemark(IpBlackDatum black, string remark)
        {
            if (black.IsDrop)
            {
                throw new ErrorException("rpc.store.ipBlack.already.drop");
            }
            else if (black.Remark == remark)
            {
                return;
            }
            base.BasicDAL.SetRemark(black.Id, remark);
        }
        private void _Check(long rpcMerId, string systemType, long ip, long? endIp)
        {
            bool isExists;
            if (endIp.HasValue)
            {
                isExists = base.BasicDAL.CheckIsExists(rpcMerId, systemType, ip, endIp.Value);
            }
            else
            {
                isExists = base.BasicDAL.CheckIsExists(rpcMerId, systemType, ip);
            }
            if (isExists)
            {
                throw new ErrorException("rpc.store.ipBlack.repeat");
            }
        }
        public int Add(AddIpBlack add)
        {
            this._Check(add.RpcMerId, add.SystemType, add.Ip, add.EndIp);
            int id = base.BasicDAL.Add(add);
            this._Refresh(add);
            return id;
        }
        public int Set(IpBlackDatum black, SetIpBlack set)
        {
            if (black.IsDrop)
            {
                throw new ErrorException("rpc.store.ipBlack.already.drop");
            }
            else if (set.EndIp != black.EndIp || set.Ip != black.Ip)
            {
                this._Check(black.RpcMerId, black.SystemType, set.Ip, set.EndIp);
            }
            black = black.ConvertInto(set);
            int id = base.BasicDAL.Set(black);
            this._Refresh(black);
            return id;
        }
        private void _Refresh(AddIpBlack black)
        {
            new RefreshIpBlack
            {
                RpcMerId = black.RpcMerId,
                SystemType = black.SystemType
            }.Send(black.RpcMerId, 0);
        }
        public void Drop(IpBlackDatum black)
        {
            if (black.IsDrop)
            {
                return;
            }
            base.BasicDAL.Drop(black);
            this._Refresh(black);
        }
    }
}
